"""
---------------------------------------------------------------------
- File: app_init.py
- Date: 2025/7/12
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 生命周期事件
---------------------------------------------------------------------
"""

import importlib

from fastapi import FastAPI
from tortoise import Tortoise
from app.core.config import app_settings
from app.models.system_manage.user import User
from app.models.system_manage.role import Role

from app.models.system_manage.menu import Menu

# 数据库配置
from app.core.config import TORTOISE_ORM

# 版本
app_version = app_settings.APP_VERSION


# 初始化路由,动态导入
async def init_endpoints(app: FastAPI):
    try:
        endpoints_module_path = f"app.api.{app_version}.endpoints"
        endpoints_module = importlib.import_module(endpoints_module_path)
        app_routers = getattr(endpoints_module, "routers", [])
        # app_routers 为空
        if app_routers:
            for router in app_routers:
                app.include_router(router, prefix=f"/api/{app_version}")
        else:
            raise "聚合路由为空"
    except Exception as e:
        raise e


async def lifespan(app: FastAPI):
    print("程序开始...")
    # 1. 数据库初始化
    await init_db()
    # 2. 路由初始化
    await init_endpoints(app)
    yield
    print("程序停止")
    await Tortoise.close_connections()


# 初始化数据库
async def init_db():
    try:
        # 配置tortoise, 数据库连接
        await Tortoise.init(config=TORTOISE_ORM)
        # 生成数据库模型
        await Tortoise.generate_schemas()

        # 初始化初始数据
        if app_settings.APP_AUTO_INIT_DB and app_settings.APP_ENV == "dev":
            await init_user_data()
            await init_role_data()
            await init_menu_data()
    except Exception as e:
        print("数据库初始化错误", str(e))
        raise e


# 初始化数据表
async def init_user_data():

    init_user_dict = [
        {
            "user_no": "admin",
            "password": "$2b$12$WE9VEa6Jmc68gABLyEG12O5BsGvHsbRt/uADd7/u58xlehAvmFu5q",  # 123
            "user_name": "管理员",
            "nick_name": "系统管理员",
            "user_gender": 1,
            "user_email": "999@126.com",
            "user_phone": "18888888888",
            "role_list": [{"role_id": 1, "role_name": "超级管理员"}],
            "status": True,
            "create_by": "管理员",
        },
        {
            "user_no": "1001",
            "password": "$2b$12$WE9VEa6Jmc68gABLyEG12O5BsGvHsbRt/uADd7/u58xlehAvmFu5q",  # 123
            "user_name": "普通管理员",
            "nick_name": "普通管理员",
            "user_gender": 1,
            "user_email": "999@126.com",
            "user_phone": "18888888888",
            "role_list": [{"role_id": 2, "role_name": "管理员"}],
            "status": False,
            "create_by": "管理员",
        },
        {
            "user_no": "1002",
            "password": "$2b$12$WE9VEa6Jmc68gABLyEG12O5BsGvHsbRt/uADd7/u58xlehAvmFu5q",  # 123
            "user_name": "游客",
            "nick_name": "路人甲",
            "user_gender": 1,
            "user_email": "999@126.com",
            "user_phone": "18888888888",
            "role_list": [{"role_id": 3, "role_name": "访客"}],
            "status": True,
            "create_by": "管理员",
        },
    ]
    create_list = [User(**user) for user in init_user_dict]
    if not await User.exists():
        print("初始化用户数据表")
        await User.bulk_create(create_list)


# 初始化角色数据表
async def init_role_data():
    init_role_dict = [
        {
            "role_no": "R_SuperAdmin",
            "role_name": "超级管理员",
            "role_desc": "拥有系统最高权限",
            "status": True,
            "create_by": "管理员",
        },
        {
            "role_no": "R_Admin",
            "role_name": "管理员",
            "role_desc": "管理系统功能",
            "status": True,
            "create_by": "管理员",
        },
        {
            "role_no": "R_Visitor",
            "role_name": "访客",
            "role_desc": "只能查看部分数据",
            "status": True,
            "create_by": "管理员",
        },
    ]
    create_list = [Role(**role) for role in init_role_dict]
    if not await Role.exists():
        print("初始化角色数据表")
        await Role.bulk_create(create_list)


# 初始化菜单数据表
async def init_menu_data():
    init_menu_dict = [
        {
            "id": 1,
            "menu_name": "首页",
            "menu_type": "2",
            "icon": "expand_circle_down",
            "route_name": "home",
            "route_path": "/home",
            "component": "views/home/index",
            "order": 1,
            "parent_id": 0,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 2,
            "menu_name": "系统管理",
            "menu_type": "1",
            "icon": "unfold_more_double",
            "route_name": "system_manage",
            "route_path": "/system_manage",
            "component": "",
            "order": 1,
            "parent_id": 0,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 3,
            "menu_name": "用户管理",
            "menu_type": "2",
            "icon": "local_car_wash",
            "route_name": "user_manage",
            "route_path": "/system_manage/user_manage",
            "component": "views/system_manage/user/index",
            "order": 1,
            "parent_id": 2,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 4,
            "menu_name": "角色管理",
            "menu_type": "2",
            "icon": "more",
            "route_name": "role_manage",
            "route_path": "/system_manage/role_manage",
            "component": "views/system_manage/role/index",
            "order": 2,
            "parent_id": 2,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 5,
            "menu_name": "菜单管理",
            "menu_type": "2",
            "icon": "preview",
            "route_name": "menu_manage",
            "route_path": "/system_manage/menu_manage",
            "component": "views/system_manage/menu/index",
            "order": 3,
            "parent_id": 2,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 6,
            "menu_name": "日志管理",
            "menu_type": "2",
            "icon": "filter_none",
            "route_name": "log_manage",
            "route_path": "/system_manage/log_manage",
            "component": "views/system_manage/log/index",
            "order": 4,
            "parent_id": 2,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 7,
            "menu_name": "销售管理",
            "menu_type": "1",
            "icon": "details",
            "route_name": "sale_manage",
            "route_path": "/sale_manage",
            "component": "views/sale_manage/index",
            "order": 1,
            "parent_id": 0,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 8,
            "menu_name": "订单管理",
            "menu_type": "2",
            "icon": "view_sidebar",
            "route_name": "order_manage",
            "route_path": "/sale_manage/order_manage",
            "component": "views/sale_manage/order/index",
            "order": 1,
            "parent_id": 7,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 9,
            "menu_name": "商品管理",
            "menu_type": "2",
            "icon": "personal_video",
            "route_name": "product_manage",
            "route_path": "/sale_manage/product_manage",
            "component": "views/sale_manage/product/index",
            "order": 2,
            "parent_id": 7,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
        {
            "id": 10,
            "menu_name": "客户管理",
            "menu_type": "2",
            "icon": "event_seat",
            "route_name": "customer_manage",
            "route_path": "/sale_manage/customer_manage",
            "component": "views/sale_manage/customer/index",
            "order": 3,
            "parent_id": 7,
            "menu_meta": {},
            "status": "1",
            "redirect": "",
            "constant": False,
        },
    ]
    create_list = [Menu(**menu) for menu in init_menu_dict]
    if not await Menu.exists():
        print("初始化菜单数据表")
        await Menu.bulk_create(create_list)
